package com.example.ecommerce.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class I18nUtil {
    private static MessageSource messageSource;
    private static I18nProperties i18nProperties;

    public I18nUtil() {
    }

    @Autowired(
            required = false
    )
    public void setMessageSource(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    @Autowired(
            required = false
    )
    public void setI18nProperties(I18nProperties i18nProperties) {
        I18nUtil.i18nProperties = i18nProperties;
    }

    public static String getMessageStr(String code, String message, Locale locale, Object... args) {
        if (messageSource == null) {
            return message == null ? code : message;
        } else {
            return message != null ? messageSource.getMessage(code, args, message, locale) : messageSource.getMessage(code, args, locale);
        }
    }

    public static String getMessageStr(String code, String message, Object... args) {
        Locale locale;
        try {
            locale = LocaleContextHolder.getLocale();
        } catch (Exception var5) {
            locale = Locale.forLanguageTag(i18nProperties.getDefaultLanguage());
        }

        return getMessageStr(code, message, locale, args);
    }

    public static String getMessageStr(MCode mCode, Locale locale, Object... args) {
        return getMessageStr(mCode.getCode(), mCode.getDesc(), locale, args);
    }

    public static String getMessageStr(MCode mCode, Object... args) {
        return getMessageStr(mCode.getCode(), mCode.getDesc(), args);
    }
}
